<template>
  <el-form ref="formRef" :model="password" :rules="rules" label-width="80px">
    <el-form-item label="账号">
      <el-input v-model="password.userName" disabled style="width: 199px" />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="phoneNum" disabled style="width: 199px" />
    </el-form-item>
    <el-form-item label="验证码" prop="validateCode">
      <el-input :maxlength="6" v-model="password.validateCode" style="width: 199px" /><el-button
        type="primary"
        style="margin-left: 5px"
        @click="getValidateCode()"
        >{{ validMess }}</el-button
      >
    </el-form-item>
    <el-form-item :label="t('profile.password.newPassword')" prop="newPassword">
      <el-input
        type="password"
        :maxlength="16"
        show-password
        autocomplete="new-password"
        v-model="password.newPassword"
        style="width: 199px"
      />
    </el-form-item>
    <el-form-item :label="t('profile.password.confirmPassword')" prop="confirmPsw">
      <el-input
        type="password"
        :maxlength="16"
        show-password
        autocomplete="new-password"
        v-model="password.confirmPsw"
        style="width: 199px"
      />
    </el-form-item>
    <el-form-item>
      <XButton :title="t('common.save')" type="primary" @click="submit(formRef)" />
      <XButton :title="t('common.reset')" type="danger" @click="reset(formRef)" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" name="ResetPwd" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { updateUserPassword, getUserProfile, updatePayPassword } from '@/api/system/user/profile'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { removeTenantId } from '@/utils/auth'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { useUserStore } from '@/store/modules/user'
import * as register from '@/api/register'
const { t } = useI18n()
const message = useMessage()
const { wsCache } = useCache()
const userStore = useUserStore()
const { replace } = useRouter()
const tagsViewStore = useTagsViewStore()
const user = wsCache.get(CACHE_KEY.USER)
const formRef = ref<FormInstance>()
const validMess = ref('获取验证码')
const props = defineProps({
  types: {
    type: String,
    default: ''
  }
})
const password = reactive({
  userName: '',
  phoneNum: '',
  validateCode: '',
  newPassword: '',
  confirmPsw: ''
})
let phoneNum = ref('')
const getUserInfo = async () => {
  let datas = await getUserProfile()
  password.userName = datas.username
  password.phoneNum = datas.mobile
  phoneNum.value = password.phoneNum.slice(0, 3) + '****' + password.phoneNum.slice(-4)
}
getUserInfo()
// 表单校验
const equalToPassword = (rule, value, callback) => {
  if (password.newPassword !== value) {
    callback(new Error(t('profile.password.diffPwd')))
  } else {
    callback()
  }
}
let countNum = ref(59)
let intervalId = null as any
const countNumFun = () => {
  if (countNum.value == 0) {
    countNum.value = 59
    clearInterval(intervalId)
    validMess.value = '获取验证码'
    return
  }
  countNum.value -= 1
  validMess.value = countNum.value + '秒'
}
const getValidateCode = async () => {
  const res = await register.sendSmsCode({
    mobile: password.phoneNum,
    scene: props.types == 'user' ? 6 : 8
  })
  if (res) {
    ElNotification({
      title: '验证码信息',
      dangerouslyUseHTMLString: true,
      duration: 10000,
      message: res
    })
  }
  message.success(t('common.sendSuccess'))
  validMess.value = countNum.value + '秒'
  intervalId = setInterval(() => {
    countNumFun()
  }, 1000)
}

const validateString = (rule, value, callback) => {
  if (
    /^((?=.*[A-Za-z])(?=.*\d)|(?=.*[A-Za-z])(?=.*[!@#$%^&*()_+\-\=])|(?=.*\d)(?=.*[!@#$%^&*()_+\-\=]))[A-Za-z\d!@#$%^&*()_+\-\=]{6,16}$/.test(
      value
    )
  ) {
    return callback()
  } else {
    return callback(new Error('至少包含字母数字特殊字符两种以上'))
  }
}

const rules = reactive<FormRules>({
  validateCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: t('profile.password.newPwdMsg'), trigger: 'blur' },
    { min: 6, max: 16, message: t('profile.password.pwdRules'), trigger: 'blur' },
    { validator: validateString, trigger: 'blur' }
  ],
  confirmPsw: [
    { required: true, message: t('profile.password.cfPwdMsg'), trigger: 'blur' },
    { min: 6, max: 16, message: t('profile.password.pwdRules'), trigger: 'blur' },
    { required: true, validator: equalToPassword, trigger: 'blur' }
  ]
})
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      if (props.types == 'user') {
        await updateUserPassword(password.userName, password.validateCode, password.newPassword)
      } else {
        await updatePayPassword(password.userName, password.validateCode, password.newPassword)
      }
      message.success(t('common.updateSuccess'))
      if (props.types == 'user') {
        removeTenantId()
        await userStore.loginOut()
        tagsViewStore.delAllViews()
        if (user.user.sourceType) {
          replace('/login?redirect=/')
        } else {
          replace('/loginAdmin?redirect=/')
        }
      }
    }
  })
}
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  getUserInfo()
  formEl.resetFields()
}
</script>
